import {
  DeleteOutlined,
  MessageOutlined,
  RightOutlined,
  SendOutlined,
} from '@ant-design/icons';
import {
  Avatar,
  Button,
  Divider,
  Empty,
  Input,
  message,
  Popconfirm,
} from 'antd';
import React, { useEffect, useState } from 'react';

import ReplyBox from '@/components/ReplyBox';
import type { CommentItem } from '@/models/talk';
import { addComment, deleteComment, getCommentTree } from '@/services/Talk/api';
import { useUserIdentity } from '@/hooks';
import styles from './index.less';

const { TextArea } = Input;

interface TalkCommentProps {
  talkId: number;
  currentUserId?: string;  // 改为string以支持15位临时用户ID
  onCommentAdd?: () => void;
}

interface CommentItemProps {
  comment: CommentItem;
  talkId: number;
  currentUserId?: string;  // 改为string以支持15位临时用户ID
  onDelete: () => void;
  onReply?: (commentId: number, username: string, replyToUserId: string) => void;
  level?: number;
}

const CommentItemComponent: React.FC<CommentItemProps> = ({
  comment,
  talkId: _talkId, // eslint-disable-line @typescript-eslint/no-unused-vars
  currentUserId,
  onDelete,
  onReply,
  level = 0,
}) => {
  const [deleteLoading, setDeleteLoading] = useState(false);

  const handleDelete = async () => {
    setDeleteLoading(true);
    try {
      const result = await deleteComment(comment.id);
      if (result.code === 200) {
        message.success('删除成功');
        onDelete();
      }
    } catch (error) {
      message.error('删除失败，请重试');
    } finally {
      setDeleteLoading(false);
    }
  };

  const formatTime = (timeStr: string) => {
    try {
      const time = new Date(timeStr);
      return time
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        })
        .replace(/\//g, '-');
    } catch {
      return timeStr;
    }
  };

  const isOwner = currentUserId === comment.userId;

  return (
    <div className={`${styles.commentItem} ${styles[`level-${level}`] || ''}`}>
      <Avatar
        src={
          comment.avatar ||
          '/h:/IDEA/Projects/iiiu/ui/src/assets/images/post.png'
        }
        size={40}
        className={styles.avatar}
      />
      <div className={styles.commentContent}>
        <div className={styles.commentHeader}>
          <div className={styles.userInfo}>
            <span className={styles.username}>
              {comment.username || '匿名用户'}
            </span>
            {/* 显示回复对象（格式：AA ▸ BB） */}
            {comment.replyToUsername && (
              <>
                <span className={styles.replyArrow}> ▸ </span>
                <span className={styles.replyToUser}>
                  {comment.replyToUsername}
                </span>
              </>
            )}
          </div>
          <span className={styles.time}>{formatTime(comment.createTime)}</span>
        </div>

        <div className={styles.commentText}>{comment.content}</div>

        <div className={styles.commentActions}>
          <Button
            type="text"
            size="small"
            icon={<MessageOutlined />}
            onClick={() =>
              onReply?.(comment.id, comment.username || '匿名用户', comment.userId.toString())
            }
            className={styles.replyBtn}
          >
            回复
          </Button>
          {isOwner && (
            <Popconfirm
              title="确定要删除这条评论吗？"
              onConfirm={handleDelete}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="text"
                size="small"
                icon={<DeleteOutlined />}
                loading={deleteLoading}
                className={styles.deleteBtn}
                danger
              >
                删除
              </Button>
            </Popconfirm>
          )}
        </div>
      </div>
    </div>
  );
};

// 扁平化评论数据的函数
const flattenComments = (
  comments: CommentItem[],
  level = 0,
): Array<CommentItem & { level: number }> => {
  const result: Array<CommentItem & { level: number }> = [];

  comments.forEach((comment) => {
    result.push({ ...comment, level });
    // 兼容children和replies两个字段名
    const childComments = comment.children || comment.replies || [];
    if (childComments.length > 0) {
      result.push(...flattenComments(childComments, level + 1));
    }
  });

  return result;
};

// 渲染评论列表和回复框的函数
const renderCommentsWithReply = (
  comments: Array<CommentItem & { level: number }>,
  talkId: number,
  userId: number,
  onDelete: () => void,
  onReply: (commentId: number, username: string, replyToUserId: string) => void,
  replyingTo: number | null,
  replyingUsername: string,
  onReplySubmit: (content: string) => void,
  onCancelReply: () => void,
) => {
  const elements = [];

  for (let i = 0; i < comments.length; i++) {
    const comment = comments[i];

    // 添加评论项
    elements.push(
      <CommentItemComponent
        key={comment.id}
        comment={comment}
        talkId={talkId}
        currentUserId={userId}
        onDelete={onDelete}
        onReply={onReply}
        level={comment.level}
      />,
    );

    // 检查是否需要在此处显示回复框
    if (replyingTo && comment.id === replyingTo) {
      // 在被回复的评论后立即显示回复框
      const isTopLevelComment = comment.level === 0;
      const placeholder = isTopLevelComment
        ? '写下你的回复...'
        : `回复@${replyingUsername}：`;

      elements.push(
        <div key={`reply-${replyingTo}`} className={styles.replyBoxContainer}>
          <ReplyBox
            targetUsername={replyingUsername}
            onSubmit={onReplySubmit}
            onCancel={onCancelReply}
            placeholder={placeholder}
          />
        </div>,
      );
    }
  }

  return elements;
};

const TalkComment: React.FC<TalkCommentProps> = ({
  talkId,
  currentUserId,
  onCommentAdd,
}) => {
  const [comments, setComments] = useState<CommentItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [commentText, setCommentText] = useState('');
  const [replyingTo, setReplyingTo] = useState<number | null>(null);
  const [replyingUsername, setReplyingUsername] = useState<string>('');
  const [replyingToUserId, setReplyingToUserId] = useState<string | undefined>();
  const [canComment, setCanComment] = useState(true);

  // 当前用户ID从props获取（支持临时用户）
  const userId = currentUserId;
  const identity = useUserIdentity();

  // 检查是否可以评论（匿名用户需要完善信息）
  useEffect(() => {
    const checkCanComment = () => {
      if (identity.isLoggedIn) {
        // 已登录用户可以评论
        setCanComment(true);
      } else {
        // 匿名用户需要检查是否已填写邮箱（name会自动生成）
        const localEmail = localStorage.getItem('anonymousUserEmail');
        setCanComment(!!localEmail && !!localEmail.trim());
      }
    };

    // 初始检查
    checkCanComment();

    // 监听storage事件
    window.addEventListener('storage', checkCanComment);
    
    // 定期检查（解决同一标签页内localStorage更新的问题）
    const intervalId = setInterval(checkCanComment, 500);

    return () => {
      window.removeEventListener('storage', checkCanComment);
      clearInterval(intervalId);
    };
  }, [identity.isLoggedIn]);

  // 获取评论列表
  const fetchComments = async () => {
    setLoading(true);
    try {
      const result = await getCommentTree(talkId);
      if (result.code === 200) {
        setComments(result.data || []);
      }
    } catch (error) {
      message.error('获取评论失败');
    } finally {
      setLoading(false);
    }
  };

  // 提交评论
  const handleSubmit = async () => {
    // 检查是否可以评论
    if (!canComment) {
      message.warning('请先完善您的邮箱信息才能评论');
      return;
    }

    if (!commentText.trim()) {
      message.warning('请输入评论内容');
      return;
    }

    if (!userId) {
      message.warning('用户ID获取失败，请刷新页面');
      return;
    }

    setSubmitLoading(true);
    try {
      const result = await addComment({
        talkId,
        content: commentText.trim(),
        userId,
        // parentId不传递（顶级评论）
      });

      if (result.code === 200) {
        message.success('评论成功');
        setCommentText('');
        fetchComments();
        onCommentAdd?.();
      }
    } catch (error) {
      message.error('评论失败，请重试');
    } finally {
      setSubmitLoading(false);
    }
  };

  // 开始回复
  const handleReply = (commentId: number, username: string, replyToUserId?: string) => {
    setReplyingTo(commentId);
    setReplyingUsername(username);
    setReplyingToUserId(replyToUserId);
  };

  // 取消回复
  const handleCancelReply = () => {
    setReplyingTo(null);
    setReplyingUsername('');
    setReplyingToUserId(undefined);
  };

  // 提交回复（支持临时用户）
  const handleReplySubmit = async (content: string) => {
    if (!userId) {
      message.warning('用户ID获取失败，请刷新页面');
      return;
    }

    if (!replyingTo) {
      message.warning('回复目标不存在');
      return;
    }

    try {
      const result = await addComment({
        talkId,
        content: content.trim(),
        parentId: replyingTo,
        replyToUserId: replyingToUserId,  // 添加被回复用户的ID
        userId,
      });

      if (result.code === 200) {
        message.success('回复成功');
        handleCancelReply();
        fetchComments();
        onCommentAdd?.();
      }
    } catch (error) {
      message.error('回复失败，请重试');
    }
  };

  useEffect(() => {
    fetchComments();
  }, [talkId]);

  return (
    <div className={styles.commentContainer}>
      {/* 评论输入框 */}
      <div className={styles.commentInput}>
        <div className={styles.inputWrapper}>
          <Avatar
            src="/h:/IDEA/Projects/iiiu/ui/src/assets/images/post.png"
            size={32}
            className={styles.inputAvatar}
          />
          <div className={styles.inputContent}>
            <TextArea
              value={commentText}
              onChange={(e) => setCommentText(e.target.value)}
              placeholder={canComment ? "写下你的评论..." : "请先完善邮箱信息才能评论"}
              autoSize={{ minRows: 2, maxRows: 4 }}
              className={styles.textArea}
              maxLength={200}
              disabled={!canComment}
            />
            <div className={styles.inputActions}>
              {!canComment && (
                <span className={styles.disabledTip}>
                  请先完善邮箱信息
                </span>
              )}
              <Button
                type="primary"
                size="small"
                icon={<SendOutlined />}
                loading={submitLoading}
                onClick={handleSubmit}
                disabled={!commentText.trim() || !canComment}
                className={styles.submitBtn}
                title={!canComment ? '请先完善邮箱信息' : ''}
              >
                评论
              </Button>
            </div>
          </div>
        </div>
      </div>

      <Divider className={styles.divider} />

      {/* 评论列表 */}
      <div className={styles.commentList}>
        {loading ? (
          <div className={styles.loading}>加载中...</div>
        ) : comments.length > 0 ? (
          renderCommentsWithReply(
            flattenComments(comments),
            talkId,
            userId,
            fetchComments,
            handleReply,
            replyingTo,
            replyingUsername,
            handleReplySubmit,
            handleCancelReply,
          )
        ) : (
          <Empty
            description="暂无评论"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            className={styles.empty}
          />
        )}
      </div>
    </div>
  );
};

export default TalkComment;
